package com.vodone.v1pin.core
{
	import caurina.transitions.Tweener;
	
	import com.vodone.v1pin.component.popup.MainPopupBackground;
	import com.vodone.v1pin.component.popup.PopupBackground;
	import com.vodone.v1pin.core.event.V1webEventDispatcher;
	import com.vodone.v1pin.core.model.ConditionVO;
	import com.vodone.v1pin.core.model.MainModelLocator;
	import com.vodone.v1pin.core.utils.GoodsUtil;
	import com.vodone.v1pin.core.utils.TextUtil;
	import com.vodone.v1pin.detail.DaohuoPanel;
	import com.vodone.v1pin.detail.ProductDetailPanel;
	import com.vodone.v1pin.detail.vo.ProductDetailVO;
	import com.vodone.v1pin.detail.widgets.AddShopAlert;
	import com.vodone.v1pin.detail.widgets.HuangTip;
	import com.vodone.v1pin.help.view.FeedbackView;
	import com.vodone.v1pin.help.view.HelpView;
	import com.vodone.v1pin.help.view.HelpViewPanel;
	import com.vodone.v1pin.help.view.RegistHelpView;
	import com.vodone.v1pin.user.login.Login;
	import com.vodone.v1pin.user.login.MailResetPassword;
	import com.vodone.v1pin.user.login.RegistOK;
	import com.vodone.v1pin.user.login.ResetPassword;
	import com.vodone.v1pin.user.model.BagModelLocator;
	import com.vodone.v1pin.user.shopbag.BagView;
	import com.vodone.v1pin.userInfo.coupon.CouponProductList;
	import com.vodone.v1pin.userInfo.coupon.CouponTypesList;
	import com.vodone.v1pin.userInfo.coupon.PopUpGiftCardSearchView;
	import com.vodone.v1pin.userInfo.delegate.AddressDelegate;
	import com.vodone.v1pin.userInfo.event.CloseWindowEvent;
	import com.vodone.v1pin.userInfo.order.PopupReturnOrderView;
	import com.vodone.v1pin.userInfo.user.PopupMailOKView;
	import com.vodone.v1pin.userInfo.user.PopupMailView;
	import com.vodone.v1pin.userInfo.user.PopupMobileView;
	import com.vodone.v1pin.video.view.vo.VideoConditionVO;
	import com.vodone.v1pin.video.view.vo.VideoVO;
	import com.vodone.v1pin.video.view.widgts.VideoPlayerPopView;
	
	import flash.events.Event;
	import flash.geom.Point;
	import flash.utils.setTimeout;
	
	import mx.binding.utils.BindingUtils;
	import mx.core.Application;
	import mx.core.FlexGlobals;
	import mx.core.UIComponent;
	import mx.effects.Move;
	import mx.events.EffectEvent;
	import mx.managers.PopUpManager;

	public class MyPopUpManager
	{
		public static const DOWN:String = "down";
		public static const UP:String = "up";
		public static const ADDWINDOW:String = "add";
		public static const NEWWINDOW:String = "new";
		
		
		public function MyPopUpManager()
		{
		}
		
		private var deitalWindow:ProductDetailPanel;
		/**
		 * 登录框 
		 */		
		private var loginWindow:Login;
		/**
		 * 购物袋 
		 */		
		private var bagWindow:BagView;
		
		/**
		 * 邮箱验证
		 */		
		private var mailWindow:PopupMailView;
		
		/**
		 * 邮箱验证
		 */		
		private var registOKWindows:RegistOK;
		
		/**
		 * 邮箱验证返回页面
		 * */
		private var mailOKWindow:PopupMailOKView;
		/**
		 * 手机验证
		 */		
		private var mobileWindow:PopupMobileView;
		/**
		 * 修改密码成功页 
		 */		
		private var mailResetPassword:MailResetPassword;
		/**
		 * 退货 
		 * */
		private var returnOrderWindow:PopupReturnOrderView;
		
		/**
		 * 购物须知 
		 */		
		private var helpWindow:HelpViewPanel;
		/**
		 * 购物须知 
		 */		
		private var registHelpWindow:RegistHelpView;
		/**
		 * 用户反馈 
		 */		
		private var feedbackView:FeedbackView;
		/**
		 * 至尊卡余额查询 
		 */		
		private var giftCardView:PopUpGiftCardSearchView;
		
		/**
		 * 红包限制商品查看 
		 */		
		private var couponProductListView:CouponProductList;
		/**
		 * 红包限制分类查看 
		 */		
		private var couponTypesListView:CouponTypesList;
		
		/**
		 * 重置密码
		 * */
		private var resetPassWindow:ResetPassword;
		/**
		 * 当前打开窗口 
		 */		
		private var currentWindow:UIComponent;
		/**
		 *  视频播放窗口 
		 */	
		private var videoPlayerWindow:VideoPlayerPopView;
		
		/**
		 * 上一个打开窗口 
		 */		
		private var lastWindow:UIComponent;
		
		private var addShopAlert:AddShopAlert;
		
		private function resetWin():void
		{
			isOpenWin = false;
			trace("reset");
		}
		
		private var isOpenWin:Boolean = false;
		
		private var popBack:MainPopupBackground;
		
		public function closeAllWindow():void
		{
			if(currentWindow){
				closeCurrentView(currentWindow);
				currentWindow = null;
			}
			if(lastWindow){
				closeCurrentView(lastWindow);
				lastWindow = null;
			}
			MainModelLocator.getInstance().isWindowOpen = false;
		}
		
		
		private var isbackGround:Boolean = false;
		/**
		 * 打开窗口 
		 * @param view
		 * @param args
		 * 
		 */		
		private function popup( view:UIComponent , args:Object = null , direct:String = "up" , method:String = "new" ):void
		{
			new CloseWindowEvent(CloseWindowEvent.OPEN_WINDOW_EVENT).dispatch();
			if(currentWindow){
				var child:UIComponent = currentWindow.getChildAt(0) as UIComponent;
				if( child == view ){
					return;
				}
				if( child == deitalWindow ){
					ProductDetailPanel(child).removeListeners();
				}
			}
			if( isOpenWin ){
				return;
			}
			
//			Tweener.removeAllTweens();
			
			if( view == deitalWindow ){
				if( view ){
					view.alpha = 0;
					if( view["detailView"] && view["detailView"]["bg"]){
						view["detailView"]["bg"].alpha = 1;
					}
					ProductDetailPanel(view).addListeners();
					ProductDetailPanel(view).refresh();
				}
			}
			isOpenWin = true;
			setTimeout( resetWin , 300 );
			var bg:PopupBackground = new PopupBackground();
			var app:Application = FlexGlobals.topLevelApplication as Application;
			view.setStyle("verticalCenter",0);
			view.setStyle("horizontalCenter" , 0 );
			
			if( method == ADDWINDOW && currentWindow ){
				moveCurrentView( currentWindow );
			}else{
				if(currentWindow != null){
					closeCurrentView(currentWindow);
				}
			}
			
			popBack ||= new MainPopupBackground();
			if(popBack && !isbackGround){
				isbackGround = true;
				BindingUtils.bindProperty( popBack , "width" , app , "width" );
				BindingUtils.bindProperty( popBack , "height" , app , "height" );
				PopUpManager.addPopUp( popBack , app );
			}else{
				PopUpManager.bringToFront( popBack );
			}
			
			
			bg.addChild( view );
			bg.x = 0;
			bg.y = (direct == "up" )?app.height:-app.height;
			bg.addEventListener( Event.CLOSE , viewCloseHandler );
			BindingUtils.bindProperty( bg , "width" , app , "width" );
			BindingUtils.bindProperty( bg , "height" , app , "height" );
			PopUpManager.addPopUp( bg , app );
			PopUpManager.bringToFront( bg );
			currentWindow = bg;
			if( view.hasOwnProperty("data") && view["data"] && view["data"].hasOwnProperty("window") ){
				var winId:String;
				var productId:String;
				if(view["data"].hasOwnProperty("windowId")){
					winId = view["data"]["windowId"];
				}
				if(view["data"].hasOwnProperty("productId")){
					productId = view["data"]["productId"];
				}
				ExternalInterfaceManager.openWindow( view["data"]["window"], winId);
			}
			MainModelLocator.getInstance().isWindowOpen = true;
			var delay:Number = 0; 
			if( view.hasOwnProperty("isCreation") && view["isCreation"] ){
				delay = 0;
			}else if( view.hasOwnProperty("isCreation") && !view["isCreation"] ){
				delay = .5;
			}
			
			if( view == deitalWindow ){
				view.alpha = 0;
				bg.y = 0;
				Tweener.addTween( view,{alpha:1,time:.6,transition:"linear",onComplete:endEffect,onCompleteParams:[view],delay:0.5} );
			}else{
				Tweener.addTween( bg,{y:0,time:.6,transition:"linear",onComplete:endEffect,onCompleteParams:[bg],delay:delay} );
			}
			
		}
		
		private function endEffect( view:UIComponent ):void
		{
			Tweener.removeTweens( view );
		}
		/**
		 * 关闭窗口 
		 * @param ui
		 * 
		 */		
		private function closeCurrentView( ui:UIComponent , method:String = "rightNow" ):void
		{
			if( currentWindow == null || currentWindow.numChildren == 0 ) return;
			var window:UIComponent = currentWindow.getChildAt(0) as UIComponent;
			if( window == loginWindow){
				new CloseWindowEvent(CloseWindowEvent.CLOSE_WINDOW_LOGIN_EVENT).dispatch();
			}
			if( method == "rightNow" ){
				ExternalInterfaceManager.openWindow( "" , "" );
				PopUpManager.removePopUp( ui );
			}else{
				ExternalInterfaceManager.openWindow( "" , "" );
				if(window == deitalWindow){
					Tweener.addTween( window,{alpha:0,time:.4,transition:"linear",onComplete:effEndHandler,onCompleteParams:[ui]} );
				}else{
					Tweener.addTween( ui,{y:ui.height,time:.4,transition:"linear",onComplete:effEndHandler,onCompleteParams:[ui]} );
				}
			}
		}
		
		private function effEndHandler( ui:UIComponent ):void
		{
			PopUpManager.removePopUp( ui );
		}
		
		/**
		 * 移动窗口 
		 * @param ui
		 * 
		 */		
		private function moveCurrentView( ui:UIComponent ):void
		{
			Tweener.addTween( ui,{y:-ui.height,time:.4,transition:"linear",onComplete:endEffect,onCompleteParams:[ui]} );
			lastWindow = ui;
		}
		
		/**
		 * 点击关闭按钮关闭 
		 * @param e
		 * 
		 */		
		private function viewCloseHandler( e:Event ):void
		{
			
			ExternalInterfaceManager.openWindow( "" , "" );
			
			closeCurrentView( currentWindow , "fead" );
			currentWindow = null;
			if( lastWindow ){
				if( lastWindow.numChildren > 0 ){
					popup( lastWindow.getChildAt(0) as UIComponent , null , "down" );
					lastWindow = null;
				}
			}
		}
		public function openFeedbackView():void
		{
			feedbackView ||= new FeedbackView();
			popup( feedbackView );
		}
		public function openGiftCardView():void
		{
			giftCardView ||= new PopUpGiftCardSearchView();
			popup( giftCardView );
		}
		public function openCouponProductListView(productId:String):void
		{
			couponProductListView ||= new CouponProductList();
			couponProductListView.productId = productId;
			popup( couponProductListView );
		}
		public function openCouponTypesListView(typesId:String):void
		{
			couponTypesListView ||= new CouponTypesList();
			couponTypesListView.typeId = typesId;
			popup( couponTypesListView );
		}
		public function openDetailView( id:String , list:Array = null , method:String = "new" , goVideo:Boolean = false ):ProductDetailPanel
		{
			ExternalInterfaceManager.logID("/product/$"+id+".html");
			
			deitalWindow ||= new ProductDetailPanel();
			deitalWindow.goVideo = goVideo;
			deitalWindow.productId = "";
			deitalWindow.productId = id;
			
			
			deitalWindow.productList = ( list ||= [] );
			
			var obj:Object = {};
			obj.window = ConditionVO.DETAIL;
			obj.windowId = id
			deitalWindow.data = obj;
			popup(deitalWindow , null , UP , method );
			return deitalWindow;
		}
		
		public function openAddShopView(  method:String = "new" ):void
		{
			addShopAlert ||= new AddShopAlert();
			popup( addShopAlert ,null ,"up" , method );
		}
		
		/**
		 * 彈出登錄框 
		 * 
		 */		
		public function openLoginView( type:String = "login" , method:String = "new" ):void
		{
			loginWindow ||= new Login();
			var obj:Object = {};
			obj.window = ConditionVO.LOGIN;
			loginWindow.data = obj;
			loginWindow.currentType = type;
			popup(loginWindow , null , UP , method );
			if( type == "login" ){
				ExternalInterfaceManager.logID("/?user#login");
			}else{
				ExternalInterfaceManager.logID("/?user#register");
			}
		}
		/**
		 * 弹出播放器 
		 */		
		public function openVideoPlayerView(item:VideoVO):void
		{
			videoPlayerWindow ||= new VideoPlayerPopView();
			if(videoPlayerWindow.videoItem && videoPlayerWindow.videoItem == item)
			{
				videoPlayerWindow.replay();
			}
			else
			{
				if(videoPlayerWindow.videoItem && videoPlayerWindow.videoItem.VideoUrl == item.VideoUrl ){
					videoPlayerWindow.replay();
				}else{
					videoPlayerWindow.videoItem = item;
				}
			}
			var obj:Object = {};
			obj.window = ConditionVO.VIDEOPLAYER;
			
			
			var url:String = item.VideoUrl;
			
			ExternalInterfaceManager.logID("/?video#product_"+item.ProductCode);
			
			url = TextUtil.StringReplaceAll(url,"/","usbp");
			url = TextUtil.StringReplaceAll(url,".","usbpp");
			url = TextUtil.StringReplaceAll(url,":","usbppp");
			obj.windowId = url + "AB21" + item.ProductCode;
			obj.productId = item.ProductCode;
			videoPlayerWindow.data = obj;
			popup( videoPlayerWindow )
		}
		/**
		 * 验证邮箱 
		 */		
		public function openMailView(mail:String):void
		{
			mailWindow ||= new PopupMailView();
			mailWindow.isSendEmail = false;
			mailWindow.mailText = mail;
			
			var obj:Object = {};
			obj.window = ConditionVO.MAIL;
			mailWindow.data = obj;
			popup( mailWindow )
		}
		/**
		 * 验证手机
		 */		
		public function openMobileView(mobile:String):void
		{
			mobileWindow ||= new PopupMobileView();
			mobileWindow.mobile = mobile;
			mobileWindow.addEventListener( Event.CLOSE , mobileCloseHandler );
			
			var obj:Object = {};
			obj.window = ConditionVO.MOBILE;
			mobileWindow.data = obj;
			popup( mobileWindow )
			
		}
		/**
		 * 退货
		 */		
		public function openReturnOrderView(orderID:String):void
		{
			returnOrderWindow ||= new PopupReturnOrderView();
			returnOrderWindow.orderID = orderID;
			
			var obj:Object = {};
			obj.window = ConditionVO.RETURNORDER;
			returnOrderWindow.data = obj;
			popup( returnOrderWindow )
		}
		
		public function openMailOKView(oid:String = null , type:String = null , typeid:String = null , valicode:String = null ):void
		{
			mailOKWindow ||= new PopupMailOKView();
			mailOKWindow.verifyInfo(oid,typeid,valicode);
			var obj:Object = {};
			obj.window = ConditionVO.MAILOK;
			mailOKWindow.data = obj;
			popup( mailOKWindow )
		}
		
		/**
		 * 彈出购物袋 
		 * 
		 */		
		public function openBagView( orderId:String = null , money:Number = 0 , goodsId:String = ""):void
		{
			bagWindow ||= new BagView();
			var obj:Object = {};
			obj.window = ConditionVO.MYBAG;
			bagWindow.data = obj;
			popup( bagWindow );
			if( orderId != null ){
				BagModelLocator.getInstance().myBagControlOrResult = BagModelLocator.MYBAG;
				BagModelLocator.getInstance().myBagControlIndex = BagModelLocator.PAY;
				BagModelLocator.getInstance().userOrderId = orderId;
				BagModelLocator.getInstance().orderMoney = money;
			}
			if(goodsId != ""){
				AddressDelegate.getAddressList(addressResultHandler);
			}
			
			function addressResultHandler(obj:Object):void
			{
				BagModelLocator.getInstance().parasAddress( obj );
				BagModelLocator.getInstance().confirmCurrentGoods( goodsId );
			}
		}
		
		public function openHelpView( method:String = "new" , index:int = 0 ):void
		{
			BagModelLocator.getInstance().keep = true;
			helpWindow ||= new HelpViewPanel();
			helpWindow.index = index;
			var obj:Object = {};
			obj.window = ConditionVO.HELP;
			helpWindow.data = obj;
			popup( helpWindow ,null ,UP,method);
		}
		
		public function openRegistHelpView( method:String = "new" , index:int = 0 ):void
		{
			registHelpWindow ||= new RegistHelpView;
			var obj:Object = {};
			obj.window = ConditionVO.REGISTHELP;
			registHelpWindow.data = obj;
			popup( registHelpWindow ,null ,UP,method);
		}
		
		public function openResetPassView():void
		{
			resetPassWindow ||= new ResetPassword();
			var obj:Object = {};
			obj.window = ConditionVO.RESETPASSWORD;
			resetPassWindow.data = obj;
			popup( resetPassWindow , null , "up" , ADDWINDOW );
		}
		
		/**
		 * 弹出邮箱找回密码成功页 
		 * 
		 */		
		public function openResetPassMailViewOK( oid:String = null , type:String = null , typeid:String = null , valicode:String = null ):void
		{
			mailResetPassword ||= new MailResetPassword();
			mailResetPassword.init( oid,typeid,valicode);
			var obj:Object = {};
			obj.window = ConditionVO.RESETPWDOK;
			mailResetPassword.data = obj;
			popup( mailResetPassword , null , "up" , ADDWINDOW );
		}
		
		/**
		 * 弹出邮箱找回密码成功页 
		 * 
		 */		
		public function openRegistOK():void
		{
			registOKWindows ||= new RegistOK();
			var obj:Object = {};
			obj.window = ConditionVO.REGISTOK;
			registOKWindows.data = obj;
			popup( registOKWindows , null , "up" );
		}
		
		/**
		 * 弹出到货通知 
		 */		
		private var daohuo:DaohuoPanel;
		public function openDaohuotongzhi( product:ProductDetailVO = null ):void
		{
			daohuo ||= new DaohuoPanel();
			daohuo.productDetail = product;
			popup( daohuo );
		}
		
		private function mobileCloseHandler( e:Event ):void
		{
			new CloseWindowEvent(CloseWindowEvent.CLOSE_WINDOW_USERMESSAGE_EVENT).dispatch();
		}
		
		
		private var currentTip:HuangTip;
		public function openTip( ui:UIComponent , text:String , time:Number = 2000 ,disX:int = 0 ):void
		{
			var tip:HuangTip = new HuangTip();
			currentTip = tip;
			tip.label  = text;
			var point:Point = ui.localToGlobal( new Point(0,-50));
			tip.x = point.x + disX;
			tip.y = point.y;
			PopUpManager.addPopUp( tip , ui.parent );
			setTimeout( function():void{
				PopUpManager.removePopUp( tip );
			} , time );
		}
		
		public function removeTip():void
		{
			PopUpManager.removePopUp( currentTip );
		}
		
		private static var _instance:MyPopUpManager;
		public static function getInstance():MyPopUpManager
		{
			if( null == _instance )
			{
				_instance = new MyPopUpManager();
			}
			return _instance;
		}
	}
}